package cs.upt.awp.services;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import cs.upt.awp.dao.UsersDAO;
import cs.upt.awp.data.UserRole;

@Service("userDetailsService")
public class TravelUserDetailsService implements UserDetailsService {
	
	Logger logger = LoggerFactory.getLogger(TravelUserDetailsService.class);

	@Autowired
	private UsersDAO userDao;

	@Transactional(readOnly = true)
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		cs.upt.awp.data.User user = userDao.findByUserName(username);
		logger.debug("****entered loadUserByUsername username: " +username);
		System.out.println("username: " +username );
		List<GrantedAuthority> authorities = buildUserAuthority(user.getUserRole());
		return buildUserForAuthentication(user, authorities);
		
	}

	private User buildUserForAuthentication(cs.upt.awp.data.User user,List<GrantedAuthority> authorities) {
		logger.debug("****entered buildUserForAuthentication user: " +user + " authorities: "+authorities);
		return new User(user.getUserName(), user.getPassword(),
				user.isEnabled(), true, true, true, authorities);
	}

	private List<GrantedAuthority> buildUserAuthority(Set<UserRole> userRoles) {
		logger.debug("****entered buildUserAuthority userRoles: " +userRoles);
		Set<GrantedAuthority> setAuths = new HashSet<GrantedAuthority>();
		// Build user's authorities
		for (UserRole userRole : userRoles) {
			setAuths.add(new SimpleGrantedAuthority(userRole.getRole()));
		}
		List<GrantedAuthority> authorities = new ArrayList<GrantedAuthority>(setAuths);
		logger.debug("****entered buildUserAuthority authorities: " +authorities);
		return authorities;
	}

}
